import {Injectable} from '@angular/core';

import $ from 'jquery';

import request from 'superagent';

import {conf} from '../config';

import {LoginPage} from '../pages/tab-my/tab-my-login';
import { Storage, LocalStorage } from 'ionic-angular';

@Injectable({
  template: '<ion-content></ion-content>'
})
export class Backend {
  constructor() {
    
    this.logined = new Storage(LocalStorage);
    // this.logined.set('version', '1.0.0.0');
    // this.logined.set('email', '');
    // this.logined.set('uid', '');
    // this.logined.set('username', '');
    // this.logined.set('groupid', '');
    
  }

  dsQuery(params) {
    return new Promise(resolve => {
      request
        .post(`${conf.server.addr}/app/query`)
        .send(params)
        .end((err, res) => {
           console.log(res);
          resolve(res.body);
        });
    });
  }

  dsFind(params) {
    return new Promise(resolve => {
      request
        .get(`${conf.server.addr}/app/find.json`)
        .query(params)
        .end((err, res) => {
          console.log(res);
          resolve(res.body);
        });
    });
  }

  isLogined() {

    return new Promise(resolve => {
      console.log(this.logined.get('didTutorial').__zone_symbol__value);
      resolve({ 'didTutorial': this.logined.get('didTutorial').__zone_symbol__value, 'email': this.logined.get('email').__zone_symbol__value, 'uid': this.logined.get('uid').__zone_symbol__value , 'groupid': this.logined.get('groupid').__zone_symbol__value, 'version': this.logined.get('version').__zone_symbol__value});
    });
  }

  // login(username, password) {
  //   return new Promise(resolve => {
  //     if (username == 'test' && password == '123456') {
  //       this.logined = true;
  //       return resolve({ status: 0, user: { username: username } });
  //     } else {
  //       return resolve({ status: 1 });
  //     }
  //   });
  // }

  login(email, password) {
    return new Promise(resolve => {

      $.post(`${conf.server.maddr}/e/api/getUser.php?type=login`,
        { mail: email, password: password })
        .done((data) => {
          let result = JSON.parse(data);
          console.log(result);
          resolve(result);
          if (result.code == '1') {
            
            this.logined.set('didTutorial', 'true');
            
            this.logined.set('email', email);
            this.logined.set('username', result.result[0].username);
            console.log(result.result[0].userid);
            this.logined.set('uid', result.result[0].userid);
            this.logined.set('groupid', result.result[0].groupid);
            
          }
          console.log(this.logined);
          console.log(this.logined.get('didTutorial').__zone_symbol__value);
        });
    });
  }

  /**
   * 取消订单
   */
  cancel(uid, id) {
    return new Promise(resolve => {
      
      $.get(`${conf.server.maddr}/php/user/order_app.php?act=cancel`,
        { userid: uid, oid: id })
        .done((data) => {
          let result = JSON.parse(data);
          console.log(result);
          resolve(result);
        });
    });

  }
  // cancel(uid, id) {
  //   return new Promise(resolve => {
  //     request
  //       .get('http://gti.ftbj.net/php/user/order_app.php?act=cancel&&uesrid=' + uid+'&&oid='+id)
  //       .end((err, res) => {
  //         console.log(res.text);        
  //         resolve(JSON.parse(res.text));         
  //       });
  //   });
  // }

  submit(uid, data) {
    return new Promise(resolve => {

      $.post(`${conf.server.maddr}/e/api/getUser.php?type=edit_member`,
        { uid: uid, data: data })
        .done((data) => {
          let result = JSON.parse(data);
          console.log(result);
          resolve(result);
        });
    });
  }

  changepassword(uid, password, newpassword) {
    return new Promise(resolve => {

      $.post(`${conf.server.maddr}/e/api/getUser.php?type=change_password`,
        { uid: uid, oldpassword: password, password: newpassword })
        .done((data) => {
          let result = JSON.parse(data);
          console.log(result);
          resolve(result);
        });
    });
  }

  loginsuccess() {
    this.uid = this.logined.get('uid').__zone_symbol__value;
    return new Promise(resolve => {
      request
        .get(`${conf.server.maddr}/e/api/getUser.php?type=info&uid=` + this.uid)
        .end((err, res) => {
          console.log(JSON.parse(res.text));
          resolve(JSON.parse(res.text));
        });
    });
  }

  forgetpasw(email) {
    return new Promise(resolve => {
      request
        .get(`${conf.server.maddr}/php/user/user.php?act=app_getpass&email=` + email)
        .end((err, res) => {
          console.log(res.text);
          if (res.text == 'Invalid user') {
            resolve(res.text);
          } else {
            resolve(JSON.parse(res.text));
          }

        });
    });
  }

  logout() {
    this.logined = false;
    this.logined.set('didTutorial', 'false');

    this.logined.set('email', '');
    this.logined.set('username','');
    
    this.logined.set('uid', '');
  }

  // 确保登录
  ensureLogined(nav) {
    return new Promise((resolve) => {
      if (this.logined.get('didTutorial').__zone_symbol__value=='true') {
        resolve(true);
      } else {
        nav.pop();
        nav.push(LoginPage, { resolve: resolve });
      }
    });
  }

  /**
   * 获取about分类
   */
  aboutCats() {
    return new Promise(resolve => {
      resolve([
        { 'id': '1', 'name': 'Who we are' },
        { 'id': '2', 'name': 'Technical Work' },
        { 'id': '3', 'name': 'Members' },
        { 'id': '4', 'name': 'Steering Committee' },
        { 'id': '5', 'name': 'PFLC' },
      ]);
    });
  }

  /**
   * about页分页内容
   */
  pages(item) {
    return new Promise(resolve => {
      if (item.id == 4) {
        request
          .get(`${conf.server.maddr}/v2/movie/in_theaters?city=武汉`)
          .end((err, res) => {
            console.log(res.body);
            this.wuhan = res.body;
            resolve(this.wuhan);
          });
      } else if (item.id == 5) {
        request
          .get('http://dev.ftbj.net/v2/movie/in_theaters?city=北京')
          .end((err, res) => {
            console.log(res.body);
            this.beijing = res.body;
            resolve(this.beijing);
          });
      }
    });
  }

  /**
   * 新闻列表模拟数据
   */
  news() {
    return new Promise(resolve => {
      resolve([
        { 'id': '1', 'img': 'asset/img/P1.jpg', 'name': 'name', 'job': 'job', 'company': 'company' },
        { 'id': '2', 'img': 'asset/img/P2.jpg', 'name': 'name', 'job': 'job', 'company': 'company' },
        { 'id': '3', 'img': 'asset/img/P3.jpg', 'name': 'name', 'job': 'job', 'company': 'company' },
        { 'id': '4', 'img': 'asset/img/P4.jpg', 'name': 'name', 'job': 'job', 'company': 'company' },
        { 'id': '5', 'img': 'asset/img/P5.jpg', 'name': 'name', 'job': 'job', 'company': 'company' },
        { 'id': '6', 'img': 'asset/img/P6.jpg', 'name': 'name', 'job': 'job', 'company': 'company' },
        { 'id': '7', 'img': 'asset/img/P7.jpg', 'name': 'name', 'job': 'job', 'company': 'company' },
        { 'id': '8', 'img': 'asset/img/P8.jpg', 'name': 'name', 'job': 'job', 'company': 'company' },
      ]);
    });
  }

  /**
   * 获取Events分类
   */
  eventsCats() {
    return new Promise(resolve => {
      resolve([
        { 'id': '1', 'name': 'Upcoming Events' },
        { 'id': '2', 'name': 'Previous Events' },
        { 'id': '3', 'name': 'Survey' }
      ]);
    });
  }

  /**
   * 获取新闻分类
   */
  newsCats() {
    return new Promise(resolve => {
      resolve([
        { 'id': '1', 'name': 'GTI Updates' },
        { 'id': '2', 'name': 'Industry News' }
      ]);
    });
  }

  /**
   * 获取Resources分类
   */
  resourcesCats() {
    return new Promise(resolve => {
      resolve([
        { 'id': 1, 'name': 'White Paper' },
        { 'id': 2, 'name': 'Industry Briefing' },
        { 'id': 3, 'name': 'Meeting file' }
      ]);
    });
  }

  /**
   * 获取Resources中Files列表
   */
  resourcesWhitePaper(name, pageIndex) {
if(name=="Industrybriefing"){
   return new Promise(resolve => {
      request
        .get(`${conf.server.maddr}/e/api/getNewsList.php?type=` + name + '&pageIndex=' + pageIndex+'&pageSize=4')
        .end((err, res) => {
          console.log(JSON.parse(res.text));
          resolve(JSON.parse(res.text));
        });
    });

}else if(name=="Whitepaper"){
  return new Promise(resolve => {
      request
        .get(`${conf.server.maddr}/e/api/getNewsList.php?type=` + name + '&pageIndex=' + pageIndex+'&pageSize=14')
        .end((err, res) => {
          console.log(JSON.parse(res.text));
          resolve(JSON.parse(res.text));
        });
    });
}else{
return new Promise(resolve => {
      request
        .get(`${conf.server.maddr}/e/api/getNewsList.php?type=` + name + '&pageIndex=' + pageIndex)
        .end((err, res) => {
          console.log(JSON.parse(res.text));
          resolve(JSON.parse(res.text));
        });
    });
}
    


  }

  loadSuvery() {
    return new Promise(resolve => {
      request
        .get(`${conf.server.maddr}/e/api/getSuveryList.php`)
        .end((err, res) => {
          console.log(JSON.parse(res.text));
          resolve(JSON.parse(res.text));
        });
    });
  }

  suvery(id) {
    return new Promise(resolve => {
      request
        .get(`${conf.server.maddr}/e/api/getSuveryList.php?id=` + id)
        .end((err, res) => {
          console.log(`${conf.server.maddr}/e/api/getSuveryList.php?id=` + id);
          resolve(JSON.parse(res.text));
        });
    });
  }

  /**
   * 获取文章内容
   */
  contents(id, classid) {
    return new Promise(resolve => {
      request
        .get(`${conf.server.maddr}/e/api/getNewsContent.php?classid=` + classid + '&id=' + id)
        .end((err, res) => {
          console.log(JSON.parse(res.text).result.content);
          resolve(JSON.parse(res.text).result.content);
        });
    });
  }

  /**
   * 获取文章下载列表
   */
  filesDownload(id) {
    return new Promise(resolve => {
      request
        .get(`${conf.server.maddr}/e/api/getMeetFile.php?id=` + id)
        .end((err, res) => {
          console.log(JSON.parse(res.text));
          resolve(JSON.parse(res.text).result.content);
        });
    });
  }

  /**
   * 获取用户信息
   */
  userInformation() {
    return new Promise(resolve => {
      resolve(
        { 'id': '1', 'name': 'xingchao', 'password': '123' }
      );
    });
  }

  /**
   * 获取GTI邮箱
   */
  contact() {
    return new Promise(resolve => {
      resolve([
        { 'id': '1', 'email': 'GTI_Secretarist_list@lte-tdd.org' },
        { 'id': '2', 'email': 'GTI@lte-tdd.org' }
      ]);
    });
  }

  /**
   * 获取GTI版本信息
   */
  versions() {
    return new Promise(resolve => {
      resolve(
        { 'v': '1', 'img': 'http://img3.doubanio.com/view/movie_poster_cover/spst/public/p2370646859.jpg', 'description': { 'title': 'V1.0Version description', 'text': ['1.fdhfsdhsdhsdhfdshfdsfoisdfdsfdjsjdfsgdsflkjgsiojgklsdfgkflgsfjglksfdjgifdjglg', '2.fsdklfsdfklcjkdfjodsfsldjgfgfngofhgogklwhghgssdf', '3.mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm', '4.bvbvbffbvbfdbdbbbbbbbbbbbbbbbbbbbbbbbbvbvb'] } }
      );
    });
  }
  /**
  * 获取报名会议列表
  */
  conference(uid) {
    return new Promise(resolve => {
      request
        .get(`${conf.server.maddr}/php/user/order_app.php?act=myOrders&userid=` + uid)
        .end((err, res) => {
          console.log(JSON.parse(res.text));

          resolve(JSON.parse(res.text));


        });
    });
  }

  /**
   * 获取个人详细信息
   */
  Information() {
    return new Promise(resolve => {
      resolve(
        { 'id': '1', 'email': 'xingchao@qq.com', 'title1': 'Mr.', 'firstname': 'xing', 'lastname': 'chao', 'mobilenumber': '18888888888', 'industrytype': 'Media', 'companyname': 'fenxingkeji', 'department': 'lalalal', 'jobtitle': 'haahahha', 'title2': 'Mr.', 'fullname': 'beijingfenxingkeji', 'contactEmail': 'fenxing@ff.com' }
      );
    });
  }

  register(fname, lname, email, username, password, repassword) {
    return new Promise(resolve => {
      $.post(`${conf.server.maddr}/e/api/getUser.php?type=signup`,
        { fname: fname, lname: lname, email: email, username: username, password: password, repassword: repassword })
        .done((data) => {
          let result = JSON.parse(data);
          console.log(result);
          resolve(result);
        });
    });
  }

/**
 * 提交调查问卷
 */
  suveryInfo(answer){
    return new Promise(resolve => {
      $.post(`${conf.server.maddr}/e/extend/helpus/ajax.php`,
       answer)
        .done((data) => {
          let result = JSON.parse(data);
          
          resolve(result);
        });
    });
  }

  meetingdetails(id) {
    return new Promise(resolve => {
      request
        .get(`${conf.server.maddr}/e/api/getMeetList.php?id=` + id)
        .end((err, res) => {    
              console.log(res,444);
          resolve(JSON.parse(res.text));
        });
    });
  }

  /**
   * 会议报名
   */
  signup(email, id) {
    return new Promise(resolve => {
      request
        .get(`${conf.server.maddr}/php/user/user.php?act=app_next&mid=` + id + '&email=' + email)
        .end((err, res) => {
          console.log(JSON.parse(res.text));
          resolve(JSON.parse(res.text));
        });
    });
  }
  /**
   * 生成订单
   */
  addorder(act, email, id, Title, First_Name, Last_Name, Mobile_Number, Industry_Type, Company_Name, Department, Job_Title) {
    return new Promise(resolve => {

      $.post(`${conf.server.maddr}/php/user/order_app.php`,
        { act: act, email: email, mid: id, Title: Title, First_Name: First_Name, Last_Name: Last_Name, Mobile_Number: Mobile_Number, Industry_Type: Industry_Type, Company_Name: Company_Name, Department: Department, Job_Title: Job_Title })
        .done((data) => {
          let result = JSON.parse(data);
          console.log(result);
          resolve(result);

        });
    });
  }

  fileDownload(url, fileName) {
    console.log(url);

    cordova.InAppBrowser.open(url, '_system', 'location=no');
    
    let saveFileName = fileName;
    if(!saveFileName) {
      saveFileName = url.replace(/^.*(\\|\/|\:)/, '');
    } 

    window.plugins.toast.showShortCenter('download start');

    window.resolveLocalFileSystemURL(cordova.file.dataDirectory, (dirEntry) => {
      
      dirEntry.getFile(saveFileName, { create: true, exclusive: false },
        (fileEntry) => {

          var fileTransfer = new FileTransfer();
          var fileURL = fileEntry.toURL();

          fileTransfer.download(
              url,
              fileURL,
              function (entry) {
                console.log('下载成功！' + entry.toURL());
                window.plugins.toast.showLongCenter('download success！\n' + entry.toURL());

                cordova.InAppBrowser.open(entry.toURL(), '_system', 'location=no');

              },
              function (error) {
                console.log(error);
                console.log('下载失败！');
              }
            );
        }, (errorCreateFile) => {
          console.log(errorCreateFile);
        });
    }, (errorLoadFs) => {
      console.log(errorLoadFs);
    });
  }

  meetinggroup(meeting,ggroup) {
    return new Promise(resolve => {
      request
        .get(`${conf.server.maddr}/e/action/AppListInfo.php?classid=494&ph=1&meeting=` + meeting+'&ggroup='+ggroup)
        .end((err, res) => {

            console.log(JSON.parse(res.text));
          resolve(JSON.parse(res.text));

        });
    });
  }

  //下载权限判断
privileges(groupid){
  return new Promise(resolve => {
      request
        .get(`${conf.server.maddr}/e/api/wspowerthan.php?group_id=` + groupid)
        .end((err, res) => {

            console.log(JSON.parse(res.text));
          resolve(JSON.parse(res.text));

        });
    });
}
}
